package vboot.core.framework.security.authc;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Component;
import vboot.core.common.mvc.dao.JdbcDao;
import vboot.core.framework.security.pojo.UserDo;

import java.util.List;

//服务于认证Service，提供组织架构相关逻辑处理
@Component
public class AuthcOrgHandler {

    //获取组织架构可用集
    public String findConds(UserDo duser) {
        StringBuilder conds = new StringBuilder();
        //1. conds拼接父级id
        if (StrUtil.isNotBlank(duser.getTier())) {
            String[] pidArr = duser.getTier().split("x");
            for (int i = pidArr.length - 1; i >= 0; i--) {
                if (!"".equals(pidArr[i])) {
                    conds.append("'").append(pidArr[i]).append("',");
                }
            }
        } else {
            conds = new StringBuilder("'" + duser.getId() + "',");
        }
        //2. conds拼接岗位id
        List<String> postList = findPostList(duser.getId());
        for (String str : postList) {
            conds.append("'").append(str).append("',");
        }
        conds = new StringBuilder(conds.substring(0, conds.length() - 1));//优化
        //3. conds拼接群组id
        List<String> groupList = findGroupList(conds.toString());
        for (String str : groupList) {
            conds.append(",'").append(str).append("'");
        }
        return conds.toString();
    }

    //获取组织架构岗位id集合
    private List<String> findPostList(String uid) {
        String sql = "select pid as id from sys_org_post_org where oid=?";
        return jdbcDao.findStringList(sql, uid);
    }

    //获取组织架构群组id集合
    private List<String> findGroupList(String conds) {
        String sql = "select DISTINCT gid as id from sys_org_group_org where oid in (" + conds + ")";
        return jdbcDao.findStringList(sql);
    }

    public String findCoopConds(UserDo duser) {
        StringBuilder conds = new StringBuilder();
        //1. conds拼接父级id
        if (StrUtil.isNotBlank(duser.getTier())) {
            String[] pidArr = duser.getTier().split("x");
            for (int i = pidArr.length - 1; i >= 0; i--) {
                if (!"".equals(pidArr[i])) {
                    conds.append("'").append(pidArr[i]).append("',");
                }
            }
        } else {
            conds = new StringBuilder("'" + duser.getId() + "',");
        }
        conds = new StringBuilder(conds.substring(0, conds.length() - 1));//优化
        return conds.toString();
    }

    @Autowired
    private JdbcDao jdbcDao;
}
